import 'dart:async';

import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/entity/widget_action_entity.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/modle/person/bloc/bank_list_bloc.dart';
import 'package:shopping_group/modle/person/entity/cust_bankInfo_entity.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/res/dimens.dart';
import 'package:shopping_group/utils/object_util.dart';
import 'package:shopping_group/utils/route_util.dart';
import 'package:shopping_group/utils/widget_utils.dart';
import 'package:bot_toast/bot_toast.dart';
import 'add_bank_page.dart';
import 'bank_details_page.dart';
import 'modify_bank_page.dart';

class BankListPage extends StatefulWidget {
  final String txType;
  BankListPage({Key key, this.txType}) : super(key: key);

  @override
  _BankListPageState createState() => _BankListPageState();
}

class _BankListPageState extends State<BankListPage> {
  List<WidgetActionEntity> _actionList = [];

  List<CustBankInfoEntity> _listEntity = [];
  ScrollController _scrollController = ScrollController();
  BankListBloc _bloc;
  StreamSubscription _refresSubscription;
  @override
  void initState() {
    super.initState();
    _bloc = BankListBloc();
    _bloc.initDate.add(null);
    _actionList
      ..add(WidgetActionEntity()
        ..actionType = 'text'
        ..title = '添加账户'
        ..titleSize = Dimens.FONT_SIZE_14
        ..actionColor = Colours.title_white);

    _refresSubscription = eventBus.on<RefreshEvent>().listen((event) {
      _bloc.initDate.add(null);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: WidgetUtils.showAppar(context, this.widget.txType,
          actionList: _actionList, textColor: Colors.white, isHide: false, onTapCall: (e) {
        // if (!BaseConstant.isRealNameAuthen) {
        //   BotToast.showText(text: '请先实名认证');
        //   return;
        // }
        RouteUtil.goParameter(AddBankPage());
      }),
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          // 触摸收起键盘
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: SafeArea(
          child: Container(
            decoration: BoxDecoration(
              color: Colours.title_white,
            ),
            child: _showlistView(),
          ),
        ),
      ),
    );
  }

  Widget _showlistView() {
    return StreamBuilder(
      stream: _bloc.sendData,
      initialData: _listEntity,
      builder: (BuildContext contexts, AsyncSnapshot<Object> snapshot) {
        Object object = snapshot.data;
        if (object is List) {
          _listEntity = object;
        }
        int count = _listEntity.length;
        if (0 != count) {
          _listEntity.forEach((element) {
            if (null == BaseConstant.bankTypeMap[element.bankType]) {
              element.imageUrl = '';
            } else {
              element.imageUrl = BaseConstant.bankTypeMap[element.bankType].imageUrl;
            }
          });
          return Container(
            decoration: new BoxDecoration(
              color: Colors.white,
            ),
            child: ListView.builder(
              controller: _scrollController,
              shrinkWrap: true,
              padding: const EdgeInsets.only(top: 4),
              itemCount: _listEntity.length,
              itemBuilder: buildItem,
            ),
          );
        } else {
          return Container(
            alignment: Alignment.center,
            child: WidgetUtils.emptyView(
              contexts,
            ),
          );
        }
      },
    );
  }

  //ListView的Item
  Widget buildItem(BuildContext context, int index) {
    return GestureDetector(
      onTap: () {
        if (ObjectUtil.isEmptyString(_listEntity[index].remark) && 'BT_ZFB' != _listEntity[index].id) {
          RouteUtil.goParameter(ModifyBankPage(entity: _listEntity[index]));
          BotToast.showText(text: '请先填写开户行信息');
        } else {
          RouteUtil.goParameter(BankDetailsPage(
            entity: _listEntity[index],
            txType: this.widget.txType,
          ));
        }
      },
      child: Container(
        color: Colours.transparent,
        child: _xunchaItem(_listEntity[index]),
      ),
    );
  }

  Widget _xunchaItem(CustBankInfoEntity entity) {
    return Container(
        decoration: BoxDecoration(
            border: Border.all(color: Colours.title_white, width: 1.0),
            borderRadius: BorderRadius.circular(15.0),
            color: Colours.title_white),
        padding: const EdgeInsets.symmetric(
          horizontal: 8,
        ),
        alignment: FractionalOffset.centerLeft,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Column(
                  children: <Widget>[
                    SizedBox(
                      height: 4,
                    ),
                    WidgetUtils.buildNetworkImageView(ObjectUtil.isEmpty(entity.imageUrl)
                        ? 'https://lizhengyouxuan.oss-cn-shanghai.aliyuncs.com/lizhengyouxuan/other/zutp.png'
                        : entity.imageUrl),
                    SizedBox(
                      height: 4,
                    ),
                  ],
                ),
                Expanded(
                  child: Container(
                    margin: EdgeInsets.only(left: 16),
                    color: Colours.transparent,
                    alignment: Alignment.centerLeft,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        WidgetUtils.getTextColorView(
                          entity.bankTypeName,
                          Colours.text_2222,
                          Dimens.FONT_SIZE_16,
                        ),
                        SizedBox(
                          height: 8,
                        ),
                        WidgetUtils.getTextColorView(
                          entity.bankNo,
                          Colours.text_2222,
                          Dimens.FONT_SIZE_16,
                        ),
                        SizedBox(
                          height: 8,
                        ),
                        WidgetUtils.getTextColorView(
                          entity.remark,
                          Colours.text_2222,
                          Dimens.FONT_SIZE_16,
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
            SizedBox(
              height: 4,
            ),
            Row(
              children: <Widget>[
                Expanded(
                  child: WidgetUtils.getTextColorView(
                    '服务费率5%',
                    Colours.text_2222,
                    Dimens.FONT_SIZE_16,
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    Map<String, dynamic> data = {};
                    data['bankInfoId'] = entity.id;
                    data['userId'] = entity.userId;
                    _bloc.deleteDate.add(data);
                  },
                  child: WidgetUtils.showBoxBotton('删除',
                      borderColor: Colours.red_606,
                      boxColor: Colours.red_606,
                      textColor: Colours.title_white,
                      borderRadius: 20,
                      horizontalPadding: 16),
                ),
              ],
            ),
            SizedBox(
              height: 4,
            ),
            WidgetUtils.drawCodeDivider(height: 1),
          ],
        ));
  }

  @override
  void dispose() {
    _refresSubscription?.cancel();
    super.dispose();
  }
}
